package net.suncaper.psychological.web.controller;

import net.suncaper.psychological.common.framework.simplemvc.RequestMapping;
import net.suncaper.psychological.model.vo.UserVO;
import net.suncaper.psychological.service.IUserService;
import net.suncaper.psychological.service.impl.UserServiceImpl;
import net.suncaper.psychological.model.dto.UserDTO;
import net.suncaper.psychological.common.utils.Result;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 用户访问控制器
 */
@RequestMapping("/api/user")
public class UserController {
    private final IUserService userService = new UserServiceImpl();

    @RequestMapping("/list.do")
    public void getUserList(HttpServletRequest request, HttpServletResponse response) {
        List<UserVO> userList = userService.getAllUsers();
        Result.success(userList).writeTo(response);
    }

    @RequestMapping("/get.do")
    public void getUserById(HttpServletRequest request, HttpServletResponse response) {
        Long id = Long.valueOf(request.getParameter("id"));
        UserVO user = userService.getUserById(id);
        Result.success(user).writeTo(response);
    }

    @RequestMapping("/add.do")
    public void addUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 设置请求和响应的字符编码
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            // 读取JSON请求体
            String jsonData = getRequestBody(request);
            System.out.println("收到添加用户请求数据: " + jsonData);
            
            // 解析JSON数据
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            // 创建UserDTO对象
            UserDTO userDTO = new UserDTO();
            userDTO.setUsername((String) data.get("username"));
            userDTO.setName((String) data.get("name"));
            userDTO.setPhone((String) data.get("phone"));
            userDTO.setGender((String) data.get("gender"));
            userDTO.setRole((String) data.get("role"));
            userDTO.setIs_active((Boolean) data.get("is_active"));
            userDTO.setExtra_info((String) data.get("extra_info"));
            userDTO.setPassword((String) data.get("password"));
            
            boolean success = userService.addUser(userDTO);
            
            // 直接创建响应，避免ThreadLocal问题
            response.setContentType("application/json;charset=UTF-8");
            if (success) {
                String jsonResponse = "{\"code\":200,\"success\":true,\"data\":\"用户添加成功\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("添加成功，返回: " + jsonResponse);
            } else {
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"用户添加失败\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("添加失败，返回: " + jsonResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"添加用户时发生错误: " + e.getMessage().replace("\"", "\\\"") + "\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("异常，返回: " + jsonResponse);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @RequestMapping("/update.do")
    public void updateUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 设置请求和响应的字符编码
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            // 读取JSON请求体
            String jsonData = getRequestBody(request);
            System.out.println("收到更新请求数据: " + jsonData);
            
            // 解析JSON数据
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            // 创建UserDTO对象
            UserDTO userDTO = new UserDTO();
            userDTO.setId(Long.valueOf(data.get("id").toString()));
            userDTO.setUsername((String) data.get("username"));
            userDTO.setName((String) data.get("name"));
            userDTO.setPhone((String) data.get("phone"));
            userDTO.setGender((String) data.get("gender"));
            userDTO.setRole((String) data.get("role"));
            userDTO.setIs_active((Boolean) data.get("is_active"));
            userDTO.setExtra_info((String) data.get("extra_info"));  // 添加这行！
            
            boolean success = userService.updateUser(userDTO);
            
            // 直接创建响应，避免ThreadLocal问题
            response.setContentType("application/json;charset=UTF-8");
            if (success) {
                String jsonResponse = "{\"code\":200,\"success\":true,\"data\":\"用户更新成功\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("更新成功，返回: " + jsonResponse);
            } else {
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"用户更新失败\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("更新失败，返回: " + jsonResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"更新用户时发生错误: " + e.getMessage().replace("\"", "\\\"") + "\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("异常，返回: " + jsonResponse);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @RequestMapping("/delete.do")
    public void deleteUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 设置请求和响应的字符编码
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            // 读取JSON请求体
            String jsonData = getRequestBody(request);
            System.out.println("收到删除请求数据: " + jsonData);
            
            // 解析JSON数据
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            Long id = Long.valueOf(data.get("id").toString());
            
            System.out.println("准备删除用户ID: " + id);
            
            // 首先检查用户是否存在
            UserVO existingUser = userService.getUserById(id);
            if (existingUser == null) {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":404,\"success\":false,\"message\":\"用户不存在\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("用户不存在，返回: " + jsonResponse);
                return;
            }
            
            boolean success = userService.deleteUser(id);
            
            // 直接创建响应，避免ThreadLocal问题
            response.setContentType("application/json;charset=UTF-8");
            if (success) {
                String jsonResponse = "{\"code\":200,\"success\":true,\"data\":\"用户删除成功\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("删除成功，返回: " + jsonResponse);
            } else {
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"用户删除失败，可能存在关联数据\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("删除失败，返回: " + jsonResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"删除用户时发生错误: " + e.getMessage().replace("\"", "\\\"") + "\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("异常，返回: " + jsonResponse);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @RequestMapping("/login.do")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 设置请求和响应的字符编码
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            // 读取JSON请求体
            String jsonData = getRequestBody(request);
            System.out.println("收到登录请求数据: " + jsonData);
            
            // 解析JSON数据
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            String username = (String) data.get("username");
            String password = (String) data.get("password");
            String role = (String) data.get("role");
            
            System.out.println("登录参数 - 用户名: " + username + ", 密码: " + password + ", 身份: " + role);
            
            UserVO user = userService.login(username, password);
            if (user != null) {
                // 如果指定了身份，验证身份是否匹配
                if (role != null && !role.isEmpty() && !role.equals(user.getRole())) {
                    response.setContentType("application/json;charset=UTF-8");
                    String jsonResponse = "{\"code\":400,\"success\":false,\"message\":\"身份不匹配，请选择正确的身份\"}";
                    response.getWriter().write(jsonResponse);
                    System.out.println("身份不匹配，返回: " + jsonResponse);
                    return;
                }
                
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":200,\"success\":true,\"data\":" + JSON.toJSONString(user) + "}";
                response.getWriter().write(jsonResponse);
                System.out.println("登录成功，返回: " + jsonResponse);
            } else {
                // 检查是否是账号被禁用的情况
                UserVO disabledUser = userService.getUserByUsername(username);
                if (disabledUser != null && !disabledUser.getIs_active()) {
                    response.setContentType("application/json;charset=UTF-8");
                    String jsonResponse = "{\"code\":403,\"success\":false,\"message\":\"账号已被禁用，请联系管理员\"}";
                    response.getWriter().write(jsonResponse);
                    System.out.println("账号被禁用，返回: " + jsonResponse);
                } else {
                    response.setContentType("application/json;charset=UTF-8");
                    String jsonResponse = "{\"code\":401,\"success\":false,\"message\":\"用户名或密码错误\"}";
                    response.getWriter().write(jsonResponse);
                    System.out.println("登录失败，返回: " + jsonResponse);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"登录时发生错误: " + e.getMessage().replace("\"", "\\\"") + "\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("异常，返回: " + jsonResponse);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @RequestMapping("/getByStudentId.do")
    public void getUserByStudentId(HttpServletRequest request, HttpServletResponse response) {
        String studentId = request.getParameter("studentId");
        UserVO user = userService.getUserByStudentId(studentId);
        if (user != null) {
            Result.success(user).writeTo(response);
        } else {
            Result.error("用户不存在").writeTo(response);
        }
    }
    
    @RequestMapping("/current.do")
    public void getCurrentUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 设置请求和响应的字符编码
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            // 从请求参数中获取用户名（学号）
            String username = request.getParameter("username");
            if (username == null || username.trim().isEmpty()) {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":400,\"success\":false,\"message\":\"用户名不能为空\"}";
                response.getWriter().write(jsonResponse);
                return;
            }
            
            System.out.println("获取当前用户信息，用户名: " + username);
            
            UserVO user = userService.getUserByUsername(username);
            if (user != null) {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":200,\"success\":true,\"data\":" + JSON.toJSONString(user) + "}";
                response.getWriter().write(jsonResponse);
                System.out.println("获取用户信息成功，返回: " + jsonResponse);
            } else {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":404,\"success\":false,\"message\":\"用户不存在\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("用户不存在，返回: " + jsonResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"获取用户信息时发生错误: " + e.getMessage().replace("\"", "\\\"") + "\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("异常，返回: " + jsonResponse);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    @RequestMapping("/profile.do")
    public void updateProfile(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 设置请求和响应的字符编码
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            // 读取JSON请求体
            String jsonData = getRequestBody(request);
            System.out.println("收到更新个人资料请求数据: " + jsonData);
            
            // 解析JSON数据
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            // 创建UserDTO对象，只更新允许修改的字段
            UserDTO userDTO = new UserDTO();
            userDTO.setId(Long.valueOf(data.get("id").toString()));
            userDTO.setUsername((String) data.get("username")); // 学号不可修改，但需要传递
            userDTO.setName((String) data.get("name")); // 姓名不可修改，但需要传递
            userDTO.setPhone((String) data.get("phone")); // 可修改
            userDTO.setGender((String) data.get("gender")); // 性别不可修改，但需要传递
            userDTO.setRole((String) data.get("role")); // 角色不可修改，但需要传递
            userDTO.setIs_active((Boolean) data.get("is_active")); // 状态不可修改，但需要传递
            userDTO.setExtra_info((String) data.get("extra_info")); // 可修改额外信息
            
            boolean success = userService.updateUser(userDTO);
            
            // 直接创建响应
            response.setContentType("application/json;charset=UTF-8");
            if (success) {
                // 返回更新后的用户信息
                UserVO updatedUser = userService.getUserById(userDTO.getId());
                String jsonResponse = "{\"code\":200,\"success\":true,\"data\":" + JSON.toJSONString(updatedUser) + ",\"message\":\"个人资料更新成功\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("个人资料更新成功，返回: " + jsonResponse);
            } else {
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"个人资料更新失败\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("个人资料更新失败，返回: " + jsonResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"更新个人资料时发生错误: " + e.getMessage().replace("\"", "\\\"") + "\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("异常，返回: " + jsonResponse);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    /**
     * 读取请求体中的JSON数据
     */
    private String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }
}
